package com.starbaba.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

@SuppressWarnings("all")
public class HttpConnection {
	public static final String POST = "post";
	public static final String GET = "get";

	public static String connection(String url, String method) {
		return connection(url, method, null);
	}

	public static String connectionZip(String url, String method,
			ArrayList<BasicNameValuePair> pair) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpUriRequest httpRequest = null;
		if (POST.equals(method)) {
			httpRequest = new HttpPost(url);
			if (pair != null) {
				HttpPost post = (HttpPost) httpRequest;
				try {
					post.setEntity(new UrlEncodedFormEntity(pair,"UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		} else if (GET.equals(method)) {
			httpRequest = new HttpGet(url);
		}
		HttpResponse execute = null;
		StringBuilder builder = new StringBuilder();
		try {
			execute = httpClient.execute(httpRequest);
			GZIPInputStream gzipInputStream = new GZIPInputStream(execute
					.getEntity().getContent());
			BufferedReader inputStream = new BufferedReader(
					new InputStreamReader(gzipInputStream,"UTF-8"));
			String line = null;
			while ((line = inputStream.readLine()) != null) {
				builder.append(line);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

	public static String connection(String url, String method,
			ArrayList<BasicNameValuePair> pair) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpUriRequest httpRequest = null;
		if (POST.equals(method)) {
			httpRequest = new HttpPost(url);
			if (pair != null) {
				HttpPost post = (HttpPost) httpRequest;
				try {
					post.setEntity(new UrlEncodedFormEntity(pair,"UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		} else if (GET.equals(method)) {
			httpRequest = new HttpGet(url);
		}
		HttpResponse execute = null;
		String result = "";
		try {
			execute = httpClient.execute(httpRequest);
			result = EntityUtils.toString(execute.getEntity(),"UTF-8");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}
